package com.fengsh.nacos.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * @标题 全局跨域配置
 * @作者 fengsh998
 * @创建时间 2024/1/31
 * @功能描述
 * 也可以通过yml文件配置
 * spring:
 *   cloud:
 *     gateway:
 *       globalcors:
 *         cors-configurations:
 *           '[/**]':
 *             allowedOriginPatterns: "*"
 *             allowedMethods: "*"
 *             allowedHeaders: "*"
 *             allowCredentials: true
 *         #解决options请求被拦截的问题
 *         add-to-simple-url-handler-mapping: true
 *
 */
@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        /// 允许所有域名
        config.addAllowedOriginPattern("*");
        /// 允许所有请求头
        config.addAllowedHeader("*");
        /// 允许所有请求method
        config.addAllowedMethod("*");
        config.addExposedHeader("*");
        /// 发送cookie
        config.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}
